#include "zrpc/base/timer.h"

#include "zrpc/net/event_loop.h"
namespace zrpc {
std::atomic<int64_t> Timer::g_num_reated = 0;

Timer::Timer(TimerCallback &&cb, TimeStamp &&expiration, bool repeat,
             double interval)
    : repeat_(repeat),
      interval_(interval),
      expiration_(std::move(expiration)),
      callback_(std::move(cb)),
      sequence_(++g_num_reated) {}

Timer::~Timer() {}

int64_t Timer::GetSequence() { return sequence_; }

TimeStamp &Timer::GetExpiration() { return expiration_; }

int64_t Timer::GetWhen() { return expiration_.GetMicroSecondsSinceEpoch(); }

bool Timer::GetRepeat() { return repeat_; }

void Timer::SetSequence(int64_t seq) { sequence_ = seq; }

double Timer::GetInterval() { return interval_; }

void Timer::Run() {
  assert(callback_ != nullptr);
  callback_();
}

void Timer::Restart(const TimeStamp &now) {
  if (repeat_) {
    expiration_ = std::move(AddTime(now, interval_));
  } else {
    expiration_ = std::move(TimeStamp::Invalid());
  }
}
}  // namespace zrpc